import {
  createRouter,
  createWebHistory
} from 'vue-router'
import Home from '../views/Home.vue'
import User from '../views/User.vue'

//使用懒加载，而不是直接导入
const HomeNews = () => import("../views/Home_news.vue");
const HomeMessage = () => import("../views/Home_news.vue");
const Profile = () => import("../views/Profile.vue");

const routes = [{
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    //元数据，用于导航守卫
    meta: {
      title: '首页'
    },
    //嵌套路由
    children: [{
        path: '',
        redirect: '/home/news'
      },
      {
        path: 'news',
        component: HomeNews
      },
      {
        path: 'message',
        component: HomeMessage
      }
    ]
  },
  {
    path: '/about',
    name: 'About',
    meta: {
      title: '关于'
    },
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    /* 
      路由懒加载：用到时再加载进来
    */
    //这是路由懒加载的方式，打包成一个js文件，而不是都放在app这个js文件里面
    component: () => import( /* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path: '/user/:userId',
    meta: {
      title: '用户'
    },
    component: User

  },
  {
    path: '/profile',
    meta: {
      title: '档案'
    },
    name:'/profile',
    component: Profile
  }
]

const router = createRouter({
  //history模式url路径上不会有#,hash模式url路径上会有#
  history: createWebHistory(process.env.BASE_URL),
  routes
})


//全局导航守卫
//前置守卫(guard),跳转前的回调
router.beforeEach((to, from, next) => {
  //从from到to
  // document.title=to.meta.title
  document.title = to.matched[0].meta.title
  next()
})

//后置钩子(hook),跳转后的回调




export default router